package com.tlvip.design.flyweight;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * <p>description：</p>
 * <p>
 * 运用共享技术有效地支持大量细粒度的对象
 * <p>
 * 优点：如果系统有大量类似的对象，可以节省大量的内存及CPU资源
 *
 * 注意点：共享对象的线程安全，数据一致性。
 *
 * JDK
 *  String,Long,Integer
 * apache
 *  com.sun.org.apache.bcel.internal.generic.InstructionConstants
 *
 * <p>copyright： copyright(C)2016-2099</p>
 * <p>Life is short,we need passion</p>
 * <p>Summary： </p>
 * <p>instructions： </p>
 * Date 2021/8/14</p>
 * Author mac
 *
 * @version 1.0
 */
public class TestFlyWeight {
    public static void main(String[] args) {
        TreeFactory treeFactory = new TreeFactory();
        TreeNode treeNode = new TreeNode(3, 4, TreeFactory.getTree("xxx", "data info"));
        TreeNode treeNode2 = new TreeNode(5, 4, TreeFactory.getTree("xxx", "data info"));
    }
}

class TreeNode {
    private int x;

    private int y;

    private Tree tree;

    public TreeNode(int x, int y, Tree tree) {
        this.x = x;
        this.y = y;
        this.tree = tree;
    }

    public int getX() {
        return x;
    }

    public void setX(int x) {
        this.x = x;
    }

    public int getY() {
        return y;
    }

    public void setY(int y) {
        this.y = y;
    }

    public Tree getTree() {
        return tree;
    }

    public void setTree(Tree tree) {
        this.tree = tree;
    }
}

class TreeFactory {
    private static Map<String, Tree> map = new ConcurrentHashMap<>();

    public static Tree getTree(String name, String data) {
        if (map.containsKey(name)) {
            return map.get(name);
        }
        // 第一次创建，后面共享使用
        Tree tree = new Tree(name, data);
        System.out.println("create tree,name:" + name);
        map.put(name, tree);
        return tree;
    }
}

class Tree {
    private final String name;
    private final String data;

    public Tree(String name, String data) {
        this.name = name;
        this.data = data;
    }

    public String getName() {
        return name;
    }

    public String getData() {
        return data;
    }
}
